/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jkoa.mgr;

import com.google.inject.Inject;
import com.jkoa.dao.PenggunaDAO;
import com.jkoa.model.Pengguna;
import com.wideplay.warp.persist.Transactional;
import org.hibernate.Query;
import org.hibernate.Session;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import net.sourceforge.stripes.util.Base64;

/**
 *
 * @author fikri
 */
public class UserManager {
    
    @Inject
    private Pengguna pengguna;
    
    @Inject
    private PenggunaDAO penggunaDAO;
    
    @Inject protected com.google.inject.Provider<Session> sessionProvider;
    
    
    
     public boolean activate(String userId) {
        Session session = sessionProvider.get();
        Query query = session.createQuery(
                "select p from Pengguna p " +
                "where idPengguna = :userId and aktif = :activate");
        query.setString("userId", userId);
        query.setString("activate", "Y");
        Pengguna user = (Pengguna) query.uniqueResult();        
        return user != null;
    }
     
     public boolean authenticate(String userId, String password) {
        String encrypted = encrypt(password);
         System.out.println("encrypted = " + encrypted);
        Session session = sessionProvider.get();
        Query query = session.createQuery(
                "select u from Pengguna u " +
                "where idPengguna = :userId and password = :password");
        query.setString("userId", userId);
        query.setString("password", encrypted);

        Pengguna user = (Pengguna) query.uniqueResult();
        return user != null;
    }
     
     public Pengguna findByUserId(String userId) {
         Session session = sessionProvider.get();
        Query query = session.createQuery(
                "select p from Pengguna p " +
                "where idPengguna = :userId and aktif = :activate");
        query.setString("userId", userId);
        query.setString("activate", "Y");
        Pengguna user = (Pengguna) query.uniqueResult();
        return user;
    }
     
     private synchronized String encrypt(String plainText) {
        MessageDigest md;

        try {
            md = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            String msg = "SHA not found, encryption cannot continue, no recovery possible";
            throw new RuntimeException(msg, e);
        }

        try {
            md.update(plainText.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            String msg = "UTF-8 encoding not found, no recovery possible";
            throw new RuntimeException(msg, e);
        }

        byte[] raw = md.digest();

        //String pwd = new BASE64Encoder().encode(raw);
        String pwd = Base64.encodeBytes(raw);
        return pwd.length() > 50 ? pwd.substring(0, 50) : pwd;
    }
     
 @Transactional     
     public Pengguna savePengguna(Pengguna p) {
         String ecrypt = encrypt(p.getPassword());
         p.setPassword(ecrypt);
        return penggunaDAO.saveOrUpdate(p);
    }
     
 @Transactional
    public void deletePengguna(Pengguna p) {
        penggunaDAO.delete(p);
    }
     
      public List<Pengguna> findAll() {
        String query = "SELECT a FROM com.jkoa.model.Pengguna a WHERE a.aktif = 'Y' ";
        Query q = sessionProvider.get().createQuery(query);
        return q.list();
    }   
    
}
